<?php
  /**
   * Set script timezone
   */     
  date_default_timezone_set(TIME_ZONE);
  /**
   * Check if config meets minimum requirements...
   */     
  if(implode('',explode('.',substr(PHP_VERSION,0,3)))<52)
  {
    die('You need at least php 5.2 to run this. Make sure you have sqlite and filters  extensions loaded.');
  }
  $required_extensions = array("sqlite","filter");
  
  foreach($required_extensions as $required_extension)
  {
    if(!extension_loaded($required_extension))
    {
      die('You need to load the '.$required_extension.' extension to run this');
    }
  }
  /**
   * Check that folders are writable
   */
  if(!is_writable(DATA_PATH))
  {
    die('Server has no write permission to the data folder. If you can\'t use chown, try "chmod 777 '.DATA_PATH.'"');
  }
  /**
   *set error display
   */     
  if(APP_DEBUG)
  {
    define(ERROR_REPORT,E_ALL|E_STRICT);
    define(ERROR_DISPLAY,true);
  }
  else
  {
    define(ERROR_REPORT,0);
    define(ERROR_DISPLAY,false);
  }
  error_reporting(ERROR_REPORT);
  ini_set('display_errors',ERROR_DISPLAY);
  /**
   *forbid session id as get parameter
   */     
  ini_set('session.use_trans_sid', false);
  /**
   *End Of Line
   */     
  define('EOL',"\r\n");
  /**
   * class loader
   */     
  function defaultClassLoader($class)
  {
    $classes = array(
      'getID3'          =>  LIB_PATH.'getid3/getid3.php',
      'getid3_writetags'=>  LIB_PATH.'getid3/write.php',
      'Tools'           =>  LIB_PATH.'mcz/Tools.class.php',
      'Scrobbler'       =>  LIB_PATH.'mcz/Scrobbler.class.php',
      'JSON'            =>  LIB_PATH.'mcz/JSON.php',
      'Html'            =>  LIB_PATH.'mcz/Html.class.php',
      'Scrobbler'       =>  LIB_PATH.'mcz/Scrobbler.class.php',
      'dbSql'           =>  LIB_PATH.'mcz/dbSql.class.php',
      'Gif'             =>  LIB_PATH.'mcz/Image.class.php',
      'Jpg'             =>  LIB_PATH.'mcz/Image.class.php',
      'Png'             =>  LIB_PATH.'mcz/Image.class.php',
      'Image'           =>  LIB_PATH.'mcz/Image.class.php',
      'File'            =>  LIB_PATH.'mcz/File.class.php',
      'CueList'         =>  APP_PATH.'app/mvc/m/CueList.class.php',
      'ImportCue'       =>  APP_PATH.'app/mvc/m/ImportCue.class.php',
      'User'            =>  APP_PATH.'app/mvc/m/User.class.php',
      'Group'           =>  APP_PATH.'app/mvc/m/Group.class.php',
      'Song'            =>  APP_PATH.'app/mvc/m/Song.class.php',
      'PlayList'        =>  APP_PATH.'app/mvc/m/PlayList.class.php',
      'PodcastReader'   =>  APP_PATH.'app/mvc/m/PodcastReader.class.php',
      'MczSession'      =>  APP_PATH.'app/mvc/m/MczSession.class.php',
      'ResultSet'       =>  APP_PATH.'app/mvc/m/ResultSet.class.php'
    );
    if(array_key_exists($class,$classes))
    {
      if(!defined('INC_FILE_'.md5($classes[$class])))
      {
          require($classes[$class]);
          define('INC_FILE_'.md5($classes[$class]),TRUE);
      }
    }
    else
    {
      die('Missing class "'.$class.'"');
    }

  }
  /**
   *Register default class loader
   */     
  spl_autoload_register('defaultClassLoader');
  
  /**
   *Implicit Exception handler
   */
  function exception_handler($exception)
  {
    if(APP_DEBUG)
    {
      $msgT = 'Uncaught Exception in '.APP_NAME;
      $msgC = $exception->getMessage()
            .EOL.EOL.'File : '.$exception->getFile()
            .EOL.'Line : '.$exception->getLine()
            .EOL.EOL.$exception->getTraceAsString();
      if(SEND_EXCEPTION){mail(DEV_MAIL,$msgT,$msgC);}
      echo(nl2br($msgT.EOL.$msgC));
      Tools::debugInfos();
    }
    else
    {
      die("An unexpected error occured. The progam died.");
    }
  }
  set_exception_handler('exception_handler');

  /**
   *sqlite/import helper, convert diacritics to their 7bit equivalent.
   *Can use HTML entities.
   *
   *@param string $string String to convert
   *@param boolean $entities wether the string has html entities or not
   *@return string
   */
  function noDiacritics($string,$entities = true)
  {
    if($entities)
    {
      $string = html_entity_decode($string,ENT_QUOTES);
    }
    $ascii_string= strtr($string,utf8_decode("ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ"),
                                "AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn");
    return $ascii_string;
  }

  /**
   * Remove magic quotes
   */
  if(get_magic_quotes_gpc() == 1)
  {
    if(!empty($_POST))
    {
      Tools::remove_magic_quotes($_POST);
    }
    if(!empty($_GET))
    {
      Tools::remove_magic_quotes($_GET);
    }
  }
  /**
   * First-time run only, check if db file exists and if not install it
   * 
   * Default admin password is 'mczadmin'
   */
   if(!is_file(DB_PATH))
   {
    $dbh = new dbSql();
    $dbh->exec(file_get_contents(APP_PATH.'app/db.sql'));
    sleep(2);// prevent file lock with winnt
    chmod(DB_PATH,0777);
   }
   
  /**
   * Start session
   */
  session_name(md5(APP_NAME));
  session_start();
  //session_regenerate_id();
  
  if(!isset($_SESSION['MczSession']))
  {
    $_SESSION['MczSession'] = new MczSession();
  }
    /**
   *Parse language file according to session value
   */
  define('LANG_CODE',$_SESSION['MczSession']->lang());
  if(is_file(APP_PATH.'app/lng/'.LANG_CODE.'.ini'))
  {
    $s = parse_ini_file(APP_PATH.'app/lng/'.LANG_CODE.'.ini');
  }
  else
  {
    $s = parse_ini_file(APP_PATH.'app/lng/en.ini');
  }
  foreach($s as $key=>$value)
  {
    define('STR_'.strtoupper($key),$value);
  }
  /**
   * Authentication
   */
  if(isset($_POST['login']) and isset($_POST['pass']) and $_POST['token'] == $_SESSION['MczSession']->getToken())
  {
    $login  = filter_input(INPUT_POST, 'login', FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
    $pass   = filter_input(INPUT_POST, 'pass', FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
    $_SESSION['MczSession']->logIn($login,$pass);
  }
  /**
   * Finally call the main controller
   */
   include(APP_PATH.'app/mvc/c/main_c.php');
?>
